package com.joymedia.thor.page;

import java.io.Serializable;

/**
 * @author XSH
 */
public abstract class AbstractPageRequest implements Pageable, Serializable {

    private final int page;
    private final int size;

    /**
     * @param page 必须不能小于1
     * @param size 必须不能小于1
     */
    public AbstractPageRequest(int page, int size) {

        if (page < 1) {
            throw new IllegalArgumentException("Page index must not be less than zero!");
        }

        if (size < 1) {
            throw new IllegalArgumentException("Page size must not be less than one!");
        }

        this.page = page;
        this.size = size;
    }

    @Override
    public int getPageSize() {
        return size;
    }

    @Override
    public int getPageNumber() {
        return page;
    }

    @Override
    public int getOffset() {
        return (page - 1) * size;
    }

    public boolean hasPrevious() {
        return page > 0;
    }

    @Override
    public Pageable previousOrFirst() {
        return hasPrevious() ? previous() : first();
    }

    /**
     * 略
     *
     * @return Pageable
     */
    @Override
    public abstract Pageable next();

    /**
     * 略
     *
     * @return Pageable
     */
    public abstract Pageable previous();

    /**
     * 略
     *
     * @return Pageable
     */
    @Override
    public abstract Pageable first();

    @Override
    public int hashCode() {

        final int prime = 31;
        int result = 1;

        result = prime * result + page;
        result = prime * result + size;

        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }

        AbstractPageRequest other = (AbstractPageRequest) obj;
        return this.page == other.page && this.size == other.size;
    }
}
